from django import forms
from django.http import JsonResponse
from django.shortcuts import render, redirect

from web import models
from utils.pager import Pagination
from utils.link import filter_reverse
from utils.response import BaseResponse
from utils.bootstrap import BootStrapForm


def policy_list(request):
    queryset = models.PriceStrategy.objects.all().order_by('count')
    pager = Pagination(request, queryset)
    context = {
        'pager': pager
    }
    return render(request, 'policy_list.html', context)


class PolicyModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.PriceStrategy
        fields = ['count', 'price']


def policy_add(request):
    if request.method == 'GET':
        form = PolicyModelForm()
        return render(request, 'form2.html', {'form': form})

    form = PolicyModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})

    form.save()
    return redirect('policy_list')


def policy_edit(request, pk):
    obj = models.PriceStrategy.objects.filter(pk=pk).first()
    if request.method == 'GET':
        form = PolicyModelForm(instance=obj)
        return render(request, 'form2.html', {'form': form})

    form = PolicyModelForm(data=request.POST, instance=obj)

    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})

    form.save()

    return redirect(filter_reverse(request, 'policy_list'))


def policy_delete(request):
    res = BaseResponse()
    if request.method == 'GET':
        cid = request.GET.get('cid')
        models.PriceStrategy.objects.filter(id=cid).delete()
        res.status = True
        return JsonResponse(res.dict)
    res.detail = '删除失败'
    return JsonResponse(res.dict)
